package com.cch.cooperation.api.zone.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cch.cooperation.api.blacklist.service.BlacklistServiceImpl;
import com.cch.cooperation.dao.file.dto.FileDTO;
import com.cch.cooperation.api.support.service.ContentCheckServiceImpl;
import com.cch.cooperation.api.zone.dto.*;
import com.cch.cooperation.biz.common.page.QueryPageProxy;
import com.cch.cooperation.biz.common.util.BeanUtilEx;
import com.cch.cooperation.common.exception.BizException;
import com.cch.cooperation.common.page.PageList;
import com.cch.cooperation.common.util.SnowflakeIdUtil;
import com.cch.cooperation.dao.blacklist.model.Blacklist;
import com.cch.cooperation.dao.zone.dto.ZoneUserDTO;
import com.cch.cooperation.dao.zone.enums.ZonePostEnum;
import com.cch.cooperation.dao.zone.mapper.ZonePostMapper;
import com.cch.cooperation.dao.zone.model.ZonePost;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ZonePostServiceImpl {

    @Resource
    private ZonePostMapper mapper;
    @Resource
    private ZoneUserServiceImpl zoneUserService;
    @Resource
    private ZonePostCommentServiceImpl zonePostCommentService;
    @Resource
    private ZonePostLikeServiceImpl zonePostLikeService;
    @Resource
    private ContentCheckServiceImpl contentCheckService;
    @Resource
    private BlacklistServiceImpl blacklistService;

    public PageList<ZonePostDTO> queryPageList(ZonePostQueryDTO req, String operatorUserId) {
        // 查询动态
        LambdaQueryWrapper<ZonePost> query = new LambdaQueryWrapper<>();
        query.eq(StrUtil.isNotEmpty(req.getId()), ZonePost::getId, req.getId());
        query.eq(StrUtil.isNotEmpty(req.getZoneId()), ZonePost::getZoneId, req.getZoneId());
        query.eq(StrUtil.isNotEmpty(req.getUserId()), ZonePost::getUserId, req.getUserId());
        // 黑名单处理
        if (StrUtil.isNotEmpty(operatorUserId)) {
            List<Blacklist> blacklists = blacklistService.queryList(operatorUserId);
            List<String> blackUserIds = blacklists.stream().map(o -> o.getTargetId()).collect(Collectors.toList());
            query.notIn(CollUtil.isNotEmpty(blackUserIds), ZonePost::getUserId, blackUserIds);
        }
        query.orderByDesc(ZonePost::getCreateTime);
        PageList<ZonePost> pageList = QueryPageProxy.query(() -> mapper.selectList(query), req.getPage(), req.getPageSize());
        // 查询发布人
        List<ZoneUserDTO> users = zoneUserService.queryList(req.getZoneId());
        Map<String, ZoneUserDTO> userMap = users.stream().collect(Collectors.toMap(o -> o.getId(), o -> o, (o1, o2) -> o1));
        // 查询评论
        List<String> zonePostIds = pageList.getRows().stream().map(o -> o.getId()).collect(Collectors.toList());
        Map<String, List<ZonePostCommentDTO>> commentMap = zonePostCommentService.getMapByZonePostIds(zonePostIds);
        // 查询点赞信息
        Map<String, List<ZonePostLikeDTO>> likeMap = zonePostLikeService.getMapByZonePostIds(zonePostIds);
        // 合并关联信息后返回
        List<ZonePostDTO> zonePosts = new ArrayList<>();
        for (ZonePost item : pageList.getRows()) {
            ZonePostDTO zonePost = BeanUtilEx.copy(item, ZonePostDTO.class);
            zonePost.setPics(StrUtil.isNotEmpty(item.getPics()) ? JSON.parseArray(item.getPics(), FileDTO.class) : null);
            zonePost.setUser(userMap.get(zonePost.getUserId()));
            zonePost.setLikes(likeMap.get(zonePost.getId()));
            zonePost.setComments(commentMap.get(zonePost.getId()));
            zonePosts.add(zonePost);
        }
        return new PageList<>(pageList.getTotal(), zonePosts);
    }

    public ZonePostDTO getById(String id) {
        ZonePost zonePost = mapper.selectById(id);
        if (ObjectUtil.isNull(zonePost)) {
            return null;
        }
        ZonePostQueryDTO query = new ZonePostQueryDTO();
        query.setId(id);
        query.setZoneId(zonePost.getZoneId());
        List<ZonePostDTO> list = queryPageList(query, null).getRows();
        return CollUtil.isNotEmpty(list) ? list.get(0) : null;
    }

    public void add(@Valid ZonePostAddDTO req) {
        if (StrUtil.isEmpty(req.getContent()) && CollUtil.isEmpty(req.getPics())) {
            throw new BizException("动态内容和图片不能都为空");
        }
        contentCheckService.checkText(req.getContent());
        ZonePost post = BeanUtilEx.copy(req, ZonePost.class);
        post.setId(SnowflakeIdUtil.getIdStr());
        if (CollUtil.isNotEmpty(req.getPics())) {
            post.setPics(JSON.toJSONString(req.getPics()));
        }
        if (Objects.isNull(post.getSourceType())) {
            post.setSourceType(ZonePostEnum.SourceType.USER_POST.value);
        }
        post.setCreateTime(new Date());
        mapper.insert(post);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String id) {
        zonePostLikeService.deleteByZonePostId(id);
        zonePostCommentService.deleteByZonePostId(id);
        mapper.deleteById(id);
    }

}
